//
//  AppDelegate.m
//  ZPFramework
//
//  Created by XuDong Jin on 14-6-30.
//  Copyright (c) 2014年 XuDong Jin. All rights reserved.
//

#import "AppDelegate.h"
#import "AppDelegate+UMShare.h"
#import "LaunchIntroductionView.h"
#import "AppDelegate+JPush.h"
#import "Launch.h"
#import "IGUrlArgumentsFilter.h"
#import "LoginViewController.h"
#import "IGRootTabBarViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import "WeiXinPayManager.h"
#import "AliPayManager.h"
#import "KeybordShowSingle.h"
#import "IGAppVersionManager.h"
#import "IGNetReachable.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self configCurrentLanguage];
    //网络模块设置
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkChanged:)
                                                 name:AFNetworkingReachabilityDidChangeNotification
                                               object:nil];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [self setup3DTouch:application];
    }
    
    //注册微信支付
    [WXApi registerApp:weiXinAppId];
    //初始化友盟
    [self initUMeng];
    //极光推送
    [self initJPushWithApplication:application withOptions:launchOptions];
    
    self.window.rootViewController = [[Launch alloc] init];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //初始化引导图，判断是否第一次启动
    if ([self isFirstLauch]) {
        [LaunchIntroductionView sharedWithImages:@[@"guide1.png", @"guide2.png", @"guide3.png", @"guide4.png"] buttonImage:@"" enterBlock:^{
            [self configRootVC];
        }];
    } else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self configRootVC];
        });
    };
    [KeybordShowSingle mainKeybordShowSingle];
    return YES;
}

- (UINavigationController *)rootNavigationController {
    UIViewController *viewController = nil;
    if (self.window.rootViewController == self.rootTabBarVC) {
        viewController = self.rootTabBarVC.selectedViewController;
    } else {
        viewController = self.window.rootViewController;
    }
    
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        return (UINavigationController *)viewController;
    } else {
        return viewController.navigationController;
    }
}
    
- (void)configRootVC {
    if (![[IGUser getUid] isEqualToString:@""]) {  //登录状态
        [self configTabBarVC];
    } else {
        [self configLoginVC];
    }
}

- (void)configLoginVC {
    [IGUser logout];
    
    _rootTabBarVC = nil;
    LoginViewController *loginVc = [[LoginViewController alloc] init];
    BaseNavigationController *loginNav = [[BaseNavigationController alloc] initWithRootViewController:loginVc];
    self.window.rootViewController = loginNav;
}

- (void)configTabBarVC {
    _rootTabBarVC = [[IGRootTabBarViewController alloc] init];
    self.window.rootViewController = _rootTabBarVC;
}

-(void)configCurrentLanguage{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] isKindOfClass:[NSString class]]) {
        [[NSUserDefaults standardUserDefaults] setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] forKey:KLanguage];
    } else {
      NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"][0];
        [[NSUserDefaults standardUserDefaults] setObject:language forKey:KLanguage];
    }
    [[NSUserDefaults standardUserDefaults] synchronize];
}


- (BOOL)isFirstLauch {
    //获取当前版本号
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentAppVersion = infoDic[@"CFBundleShortVersionString"];
    //获取上次启动应用保存的appVersion
    NSString *version = [[NSUserDefaults standardUserDefaults] objectForKey:@"appVersion"];
    //版本升级或首次登录
    if (version == nil || ![version isEqualToString:currentAppVersion]) {
        [[NSUserDefaults standardUserDefaults] setObject:currentAppVersion forKey:@"appVersion"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    } else {
        return NO;
    }
}

- (void)setup3DTouch:(UIApplication *)application {
    UIApplicationShortcutIcon *firstIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"3DTouch4"];
    UIApplicationShortcutItem *firstItem = [[UIApplicationShortcutItem alloc] initWithType:@"ONE" localizedTitle:NSLocalizedString(@"My Art Gallery", nil) localizedSubtitle:@"" icon:firstIcon userInfo:nil];
    
    UIApplicationShortcutIcon *secondIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"3DTouch3"];
    UIApplicationShortcutItem *secondItem = [[UIApplicationShortcutItem alloc] initWithType:@"TWO" localizedTitle:NSLocalizedString(@"Message Center", nil) localizedSubtitle:@"" icon:secondIcon userInfo:nil];
    
    UIApplicationShortcutIcon *thirdIcon = [UIApplicationShortcutIcon iconWithTemplateImageName:@"3DTouch2"];
    UIApplicationShortcutItem *thirdItem = [[UIApplicationShortcutItem alloc] initWithType:@"THREE" localizedTitle:NSLocalizedString(@"Device Managemen", nil) localizedSubtitle:@"" icon:thirdIcon userInfo:nil];
    /** 将items 添加到app图标 */
    application.shortcutItems = @[firstItem,secondItem,thirdItem];
}

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler
{
    if ([[IGUser getUid] isEqualToString:@""])
    {
        return;
    }
    if([shortcutItem.type isEqualToString:@"ONE"])
    {
        [UIViewController ig_pushViewControllerClass:[ArtGalleryViewController class] animated:YES];
    }
    else if ([shortcutItem.type isEqualToString:@"TWO"])
    {
        [UIViewController ig_pushViewControllerClass:[MessageViewController class] animated:YES];
    }
    else if ([shortcutItem.type isEqualToString:@"THREE"])
    {
        [UIViewController ig_pushViewControllerClass:[IGMyiGalleryVC class] animated:YES];
    }
}

// ------------------------------------------------------
/*
 由于用到支付宝所以这个方法放在 appdelegate 里)
 支持所有iOS系统
 */
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    NSURL *absoluteURL = url.absoluteURL;
    NSString *scheme = absoluteURL.scheme;
    if ([scheme isEqualToString:weiXinAppId] && [url.host isEqualToString:@"pay"])
    {
        WeiXinPayManager *manager =[WeiXinPayManager sharedManager];
        return [WXApi handleOpenURL:url delegate:manager];
    }
    
    if(!result)
    {
        AliPayManager *aliPaymana =[AliPayManager sharedAliPayManager];
        return  [aliPaymana aLiPayWithApplication:application openURL:url sourceApplication:nil annotation:nil];
    }
    
    [self UMengActionWithUrl:url];
    return result;
}

//支持目前所有iOS系统
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}

//仅支持iOS9以上系统，iOS8及以下系统不会回调
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url];
    
    NSURL *absoluteURL = url.absoluteURL;
    NSString *scheme = absoluteURL.scheme;
    if ([scheme isEqualToString:weiXinAppId] && [url.host isEqualToString:@"pay"])
    {
        WeiXinPayManager *manager =[WeiXinPayManager sharedManager];
        return [WXApi handleOpenURL:url delegate:manager];
    }
    if(!result)
    {
        AliPayManager *aliPaymana =[AliPayManager sharedAliPayManager];
        return  [aliPaymana aLiPayWithApplication:app openURL:url sourceApplication:nil annotation:nil];
    }
    return result;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 这里处理新浪微博SSO授权进入新浪微博客户端后进入后台，再返回原来应用
 */
- (void)applicationDidBecomeActive:(UIApplication *)application
{
//    [UMSocialSnsService applicationDidBecomeActive];
}

/**
 *  程序进入前台u台的时候调用
 */
- (void)applicationWillEnterForeground:(UIApplication *)application {
    application.applicationIconBadgeNumber = 0;
    //检查版本更新
    [IGAppVersionManager checkAppVersion];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if ([touches.anyObject locationInView:nil].y > 20) return;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"click" object:nil];
}

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}

- (void)networkChanged:(NSNotification *)notification {
    if (![IGNetReachable isReachable]) {
//        [self presentMessageTips:@"网络连接失败,请检查你的网络设置"];
        [self presentMessageTips:NSLocalizedString(@"Network Connection Failed, Please Check Your Network Configuration.", nil)];
    }
}
@end
